import { runCmd } from "./shell";

export async function getCurrentBranch() {
  const result = await runCmd("git branch");
  if (/\*\s([\w-\/]+)/.test(result)) {
    return RegExp.$1;
  } else {
    throw new Error("Get current branch error:" + result);
  }
}

export async function getRemoteHomeUrl() {
  const source = await runCmd("git remote -v");

  if (/git@([\w\.-]+):([\w\/-]+)\.git/.test(source)) {
    return `https://${RegExp.$1}/${RegExp.$2}`;
  } else if (/https?:\/\/([\w\.-]+):([\w\/-]+)\.git/.test(source)) {
    return source.replace(/\.git/, "");
  } else {
    throw new Error("Invalid remote:" + source);
  }
}

export async function buildCreatePrUrl(targetBranch: string) {
  const homeUrl = await getRemoteHomeUrl();
  const currentBranch = await getCurrentBranch();
  return `${homeUrl}/compare/${targetBranch}...${currentBranch}`;
}

export async function getBranches(keyword?: string): Promise<string[]> {
  const result = await runCmd("git branch -a");
  const keywords = keyword?.split(",").filter((k) => k !== "") ?? [];

  return result
    .split("\n")
    .map((branch) => branch.replace(/\s/g, ""))
    .filter((branch) => keywords.every((k) => branch.includes(k)));
}

export function getLastCommit() {
  return runCmd("git show -s --format=%s");
}